﻿using System;
using Microsoft.SharePoint;

namespace SPFluid.Core.Utilities
{
    public static class SecurityUtility
    {
        public static void RunSystemImpersonated(this SPSite site, string webUrl, Action<SPWeb> action)
        {
            RunImpersonated(site, webUrl, site.SystemAccount, action);
        }

        public static void RunSystemImpersonated(this SPWeb web, Action<SPWeb> action)
        {
            RunImpersonated(web, web.Site.SystemAccount, action);
        }

        public static T RunSystemImpersonated<T>(this SPSite site, string webUrl, Func<SPWeb, T> func)
        {
            return RunImpersonated(site, webUrl, site.SystemAccount, func);
        }

        public static T RunSystemImpersonated<T>(this SPWeb web, Func<SPWeb, T> func)
        {
            return RunImpersonated(web, web.Site.SystemAccount, func);
        }

        public static void RunImpersonated(this SPWeb web, SPUser user, Action<SPWeb> action)
        {
            using (var impersonatedSite = new SPSite(web.Url, user.UserToken))
            using (var impersonatedWeb = impersonatedSite.OpenWeb())
            {
                action(impersonatedWeb);
            }
        }

        public static void RunImpersonated(this SPSite site, string webUrl, SPUser user, Action<SPWeb> action)
        {
            using (var impersonatedSite = new SPSite(site.ID, user.UserToken))
            using (var impersonatedWeb = impersonatedSite.OpenWeb(webUrl))
            {
                action(impersonatedWeb);
            }
        }

        public static T RunImpersonated<T>(this SPWeb web, SPUser user, Func<SPWeb, T> func)
        {
            using (var impersonatedSite = new SPSite(web.Url, user.UserToken))
            using (var impersonatedWeb = impersonatedSite.OpenWeb())
            {
                return func(impersonatedWeb);
            }
        }

        public static T RunImpersonated<T>(this SPSite site, string webUrl, SPUser user, Func<SPWeb, T> func)
        {
            using (var impersonatedSite = new SPSite(site.ID, user.UserToken))
            using (var impersonatedWeb = impersonatedSite.OpenWeb(webUrl))
            {
                return func(impersonatedWeb);
            }
        }
    }
}